<?php
namespace app\controllers;
use app\models\Class1;
use app\models\Class2;
use app\models\Comment;
use app\models\DataRelationship;
use app\models\ReadContent;
use app\models\SpeakContent;
use app\models\WriteQuestion;
use yii\db\Query;
use yii\helpers\HtmlPurifier;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\Response;

class AjaxController extends Controller
{
    public function actionGetdata()
    {
        $request=\Yii::$app->request;
        if($request->isAjax) {
            $class1 = $request->get('class1');
            $class2 = $request->get('class2');
            $beginnum = $request->get('beginnum');
            $endnum=$request->get('endnum');
            if(!isset($class1)||!isset($class2))
                die();
            $class1_r=Class1::find()->select(['id'])->where(['name'=>$class1])->one();
            $class2_r=Class2::find()->select(['id'])->where(['name'=>$class2,'class1_id'=>$class1_r['id']])->one();
            switch ($class1_r['id'])
            {
                case 1:
                    if(!isset($beginnum)||!isset($endnum))
                        $r=ReadContent::find()
                            ->select(['id','title','num','info','diff','class_num','passage','img_url'])
                            ->where(['class2_id'=>$class2_r['id']])
                            ->orderBy(['class_num'=>SORT_ASC,'passage'=>SORT_ASC])
                            ->all();
                    else
                        $r=ReadContent::find()
                            ->select(['id','title','num','info','diff','class_num','passage','img_url'])
                            ->where(['between','class_num',$beginnum,$endnum])
                            ->andWhere(['class2_id'=>$class2_r['id']])
                            ->orderBy(['class_num'=>SORT_ASC,'passage'=>SORT_ASC])
                            ->all();
                    $r['class1']=$class1;
                    $r['class2']=$class2;
                    $r['class2_info']=strtoupper($class2).$beginnum.'-'.strtoupper($class2).$endnum;
                    \Yii::$app->response->format = Response::FORMAT_JSON;
                    return $r;
                    break;
                case 2:
                    $r=WriteQuestion::find()
                        ->select(['id','tnum','info','num','diff','index_img_url','class_name','class_num'])
                        ->where(['class2_id'=>$class2_r['id']])
                        ->orderBy(['class_num'=>SORT_ASC])
                        ->all();
                    $r['class1']=$class1;
                    $r['class2']=$class2;
                    $r['class2_info']=$class2;
                    \Yii::$app->response->format = Response::FORMAT_JSON;
                    return $r;
                    break;
                case 3:
                    if(!isset($beginnum)||!isset($endnum))
                        $r=SpeakContent::find()
                            ->select(['id','info','num','diff','hear_number','question_number','index_img_url'])
                            ->where(['class2_id'=>$class2_r['id']])
                            ->orderBy(['hear_number'=>SORT_ASC,'question_number'=>SORT_ASC])
                            ->all();
                    else
                        $r=SpeakContent::find()
                            ->select(['id','info','num','diff','hear_number','question_number','index_img_url'])
                            ->where(['between','hear_number',$beginnum,$endnum])
                            ->andWhere(['class2_id'=>$class2_r['id']])
                            ->orderBy(['hear_number'=>SORT_ASC,'question_number'=>SORT_ASC])
                            ->all();
                    $r['class1']=$class1;
                    $r['class2']=$class2;
                    $r['class2_info']=strtoupper($class2).$beginnum.'-'.strtoupper($class2).$endnum;
                    \Yii::$app->response->format = Response::FORMAT_JSON;
                    return $r;
                    break;
            }
        }
    }
    public function actionGetimgurl()
    {
        $request=\Yii::$app->request;
        if($request->isAjax)
        {
            $session=\Yii::$app->session;
            $session->open();
            $r=$session['imgurl'];
            if(isset($r))
            {
                if($r)
                {
                    \Yii::$app->response->format = Response::FORMAT_JSON;
                    return $r;
                }
            }
        }
        return "{error:1}";
    }
    public function actionGettime($state,$token)
    {
        $request=\Yii::$app->request;
        $session=\Yii::$app->session;
        $session->open();
        if($request->isAjax)
        {
            if($state=='begin'&&$token==$session['time_token'])
            {
                $session['begin_time']=time();
                $session['time_token']=md5($session['curr_time']."i_am_salt");
                $r['time']=0;
                \Yii::$app->response->format=Response::FORMAT_JSON;
                return $r;
            }
            elseif ($state=='next'&&$token==$session['time_token'])
            {
                $now=time();
                $last=$session['begin_time'];
                $r['time']=$now-$last;
                $session['time_token']=md5($r['time']."lalala");
                \Yii::$app->response->format=Response::FORMAT_JSON;
                return $r;
            }
        }
    }
    public function actionComment()
    {
        $request=\Yii::$app->request;
        $session=\Yii::$app->session;
        $session->open();
        if($request->isAjax)
        {
            if ($request->isGet)
            {
                $class1_id = $request->get('class1');
                $class2_id = $request->get('class2');
                $question_id = $request->get('question');
                $where = [
                    'class1_id' => $class1_id,
                    'class2_id' => $class2_id,
                    'question_id' => $question_id,
                ];
                if(Class1::findOne($class1_id)['name']=='writing')
                {
                    $select=[
                        'comment_content',
                        'comment_time',
                        'like_num',
                        'play_num',
                        'name',
                        'photo',
                        'user.user_id',
                        'like_ids',
                        'readhand1',
                        'readhand2',
                        'readhand3',
                        'listenhand1',
                        'listenhand2',
                        'listenhand3',
                        'type',
                        'content',
                        'readtheme',
                        'listentheme'
                    ];
                    $query = new Query();
                    $comment=$query
                        ->select($select)
                        ->from(['comment','user','write_person'])
                        ->where(['and','user.user_id=comment.user_id','write_person.uid=user.user_id','comment.question_id=write_person.write_question_id'])
                        ->andWhere($where)
                        ->orderBy(['is_up'=>SORT_DESC,'like_num'=>SORT_DESC,'play_num'=>SORT_DESC])
                        ->all();
                }
                else{
                    $comment = Comment::find()
                    ->select(['comment_content','url','comment_time','like_num','play_num','name','photo','user.user_id','like_ids'])
                    ->where($where)
                    ->join('LEFT JOIN','user','user.user_id=comment.user_id')
                    ->orderBy(['is_up'=>SORT_DESC,'like_num'=>SORT_DESC,'play_num'=>SORT_DESC])
                    ->asArray()
                    ->all();
                }
                \Yii::$app->response->format=Response::FORMAT_JSON;
                return $comment;
            }elseif ($request->isPost)
            {
                $class1_id = $request->post('class1');
                $class2_id = $request->post('class2');
                $question_id = $request->post('question');
                $tnum=$request->post('tnum');
                $comment_content=HtmlPurifier::process($request->post('comment'));//过滤危险标签
                $user_id = $session['user_id'];
                if(!isset($user_id))
                    die();
                $where = [
                    'class1_id' => $class1_id,
                    'class2_id' => $class2_id,
                    'question_id' => $question_id,
                    'user_id'=>$user_id
                ];
                $comment = Comment::find()->where($where)->one();
                if(!isset($comment))
                    $comment = new Comment();
                if(Class1::findOne($class1_id)['name']=='speaking')
                    $comment->url=Url::to('@web/audio/user_voice/'.md5("speaking_{$user_id}_{$question_id}").".wav");
                $comment->class1_id = $class1_id;
                $comment->class2_id = $class2_id;
                $comment->question_id = $question_id;
                $comment->user_id = $user_id;
                $class2_name=strtoupper(Class2::findOne($class2_id)['name'])."-";
                if(Class1::findOne($class1_id)['name']=='speaking')
                    $class2_name.=SpeakContent::find()
                        ->select(['hear_number'])
                        ->where(['id'=>$question_id])
                        ->one()['hear_number'];
                $comment_content.="<div style='display: none' class='selfText'>$class2_name</div>";
                $comment->comment_content=$comment_content;
                $comment->comment_time=date('Y-m-d H:i:s');
                $comment->tnum=$tnum;
                $r['state']=$comment->save();
                \Yii::$app->response->format=Response::FORMAT_JSON;
                return $r;
            }

        }
    }

    /**
     * 点赞处理
     */
    public function actionLike()
    {
        $request=\Yii::$app->request;
        $session=\Yii::$app->session;
        $session->open();
        if($request->isAjax&&$request->isPost)
        {
            $tar_id = $request->post('tar');
            $sou_id = $request->post('sou');
            $class2_id = $request->post('class2');
            $class1_id = $request->post('class1');
            $question_id = $request->post('question');
            $state = $request->post('status');
            $where = [
                'class1_id' => $class1_id,
                'class2_id' => $class2_id,
                'question_id' => $question_id,
                'user_id' => $tar_id
            ];
            $comment = Comment::find()->where($where)->one();
            if (!isset($comment)||!isset($state)||$sou_id!=$session['user_id'])
                die("{state:'error'}");
            $like_ids = json_decode($comment->like_ids);
            if ($state == 'like')
            {
                if (isset($like_ids))
                {
                    $position=array_search($sou_id, $like_ids);
                    if ($position!==false)
                        die("{state:'error'}");
                    else
                    {
                        array_push($like_ids, $sou_id);
                        $comment->like_ids = json_encode($like_ids);
                        $comment->like_num=count($like_ids);
                        $comment->save();
                        $r['state'] = 'ok';
                        \Yii::$app->response->format = Response::FORMAT_JSON;
                        return $r;
                    }
                }
            }elseif ($state=='unlike')
            {
                if (isset($like_ids))
                {
                    $position=array_search($sou_id, $like_ids);
                    if ($position===false)//没找到
                        die("{state:'error'}");
                    array_splice($like_ids,$position,1);
                    $comment->like_ids = json_encode($like_ids);
                    $comment->like_num=count($like_ids);
                    $comment->save();
                    $r['state'] = 'ok';
                    \Yii::$app->response->format = Response::FORMAT_JSON;
                    return $r;
                }
            }
        }
    }

    public function actionView()
    {
        $request=\Yii::$app->request;
        $session=\Yii::$app->session;
        $session->open();
        if($request->isAjax&&$request->isPost)
        {
            $tar_id = $request->post('tar');
            $sou_id = $request->post('sou');
            $class2_id = $request->post('class2');
            $class1_id = $request->post('class1');
            $question_id = $request->post('question');
            $where = [
                'class1_id' => $class1_id,
                'class2_id' => $class2_id,
                'question_id' => $question_id,
                'user_id' => $tar_id
            ];
            $comment = Comment::find()->where($where)->one();
            if (!isset($comment)||$sou_id!=$session['user_id'])
                die("{state:'error'}");
            $comment->play_num++;
            $comment->save();
            $r['state'] = 'ok';
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return $r;
        }
    }

    public function actionCommunity(){
        $request=\Yii::$app->request;
        if($request->isAjax)
        {
            $select = [
                'user.name as user_name',
                'play_num',
                'like_num',
                'question_id',
                'url',
                'comment_content',
                'comment_time',
                'class2.name as class2_name',
                'class1.name as class1_name',
                'class1.id as class1_id',
                'class2.id as class2_id',
                'user.user_id as tar_id',
                'like_ids',
                'tnum'
            ];
            $reading_id=Class1::find()->select(['id'])->where(['name'=>'reading'])->one()['id'];
            if($request->post('state')=='1')
            {
                $class1_name = $request->post('class');
                if (!isset($class1_name)) die();
                $class1_id = Class1::find()->select(['id'])->where(['name' => $class1_name])->one()['id'];
                $query = new Query();
                $comment = $query
                    ->select($select)
                    ->from(['comment', 'user', 'class2', 'class1'])
                    ->where(['and',
                        'user.user_id=comment.user_id',
                        "comment.class1_id= $class1_id",
                        "comment.class2_id=class2.id",
                        "comment.class1_id=class1.id",
                        "comment.class1_id<>$reading_id"
                    ])
                    ->orderBy(['like_num'=>SORT_DESC])
                    ->all();
                \Yii::$app->response->format = Response::FORMAT_JSON;
                return $comment;
            }elseif($request->post('state')=='2')
            {
                $query = new Query();
                $comment = $query
                    ->select($select)
                    ->from(['comment', 'user', 'class2', 'class1'])
                    ->where(['and',
                        'user.user_id=comment.user_id',
                        "comment.class2_id=class2.id",
                        "comment.class1_id=class1.id",
                        "comment.class1_id<>$reading_id"
                    ])
                    ->orderBy(['like_num'=>SORT_DESC])
                    ->all();
                \Yii::$app->response->format = Response::FORMAT_JSON;
                return $comment;
            }
        }
    }

    public function actionGetstate()
    {
        $request=\Yii::$app->request;
        $session=\Yii::$app->session;
        $session->open();
        if($request->isAjax)
        {
            $class1_name=$request->get('class1');
            $class1_id=Class1::find()->select(['id'])->where(['name'=>$class1_name])->one()['id'];
            $user_id=$session['user_id'];
            if(!isset($user_id)) die();
            $where=[
                'class1_id'=>$class1_id,
                'user_id'=>$user_id
            ];
            $r=DataRelationship::find()
                ->select(['content_id as id'])
                ->where($where)
                ->all();
            \Yii::$app->response->format=Response::FORMAT_JSON;
            return $r;
        }
    }

    public function actionGetwriteurl($id)
    {
        $operate = WriteQuestion::findOne($id);
        $res = $operate->url;
        echo json_encode($res);
    }

    public function actionGetwriteimgurl($id)
    {
        $operate = WriteQuestion::findOne($id);
        $res = $operate->index_img_url;
        echo json_encode($res);
    }

    public function actionGetspeakimgurl($id)
    {
        $operate = SpeakContent::findOne($id);
        $res = $operate->img_url;
        echo json_encode($res);
    }

    public function actionGetspeakdirection($id)
    {
        $operate = SpeakContent::findOne($id);
        $res = $operate->direction;
        echo json_encode($res);
    }

    public function actionGetspeaktopiccontent($id)
    {
        $operate = SpeakContent::findOne($id);
        $res = $operate->topic_content;
        echo json_encode($res);
    }

    public function actionGetspeaklistenscript($id)
    {
        $operate = SpeakContent::findOne($id);
        $res = $operate->listening_script;
        echo json_encode($res);
    }

    public function actionGetspeakreadtips($id)
    {
        $operate = SpeakContent::findOne($id);
        $res = $operate->reading_tips;
        echo json_encode($res);
    }
}